<template>
  <div>
    <!--顶栏-->
    <div id="header">
      <span class="logoText">Friend</span>
    </div>

    <div class="flex flex-row">
      <!--导航栏-->
      <div
        style="width: 5%; background-color: #f3f2ef; height: 680px"
        class="flex flex-col"
      >
        <el-image
          :src="require('@/assets/chat/logo.png')"
          class="logo"
          @click="toMain"
        ></el-image>
        <el-image
          :src="avatar"
          class="userAvatar"
          @click="transformMain"
        ></el-image>
        <el-image
          :src="require('@/assets/chat/friend.png')"
          class="icon"
          @click="getFriendListInfo"
        ></el-image>
        <el-image
          :src="require('@/assets/chat/group.png')"
          class="icon"
          @click="getGroupListInfo"
        ></el-image>
        <el-image
          :src="require('@/assets/chat/message.png')"
          class="icon"
          @click="getMessageListInfo"
        ></el-image>
        <el-image
          :src="require('@/assets/chat/gameList.png')"
          class="icon"
          v-if="(listType === 2 || listType === 3) && sendCount >= 5"
          @click="listType = 3"
        ></el-image>
      </div>

      <!--好友列表-->
      <div class="friendAndMessageList" v-if="listType === 0">
        <span class="FMTitle">Chat</span>
        <span class="subTitle">Friend List</span>

        <div style="height: 560px; overflow: auto">
          <div v-for="(item, index) in userList" :key="item">
            <div
              class="friendInfo"
              @click="transformChatMainFriend(item, index)"
            >
              <div class="AvatarBox">
                <el-image :src="item.image" class="friendAvatar"></el-image>
              </div>
              <div class="friendContent">
                <div class="username2">{{ item.name }}</div>
                <!-- <div class="content">{{item.content}}</div> -->
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="friendAndMessageList" v-if="listType === 1">
        <span class="FMTitle">Chat</span>
        <span class="subTitle">Group List</span>

        <div style="height: 560px; overflow: auto">
          <div v-for="(item, index) in groupList" :key="item">
            <div
              class="friendInfo"
              @click="transformChatMainGroup(item, index)"
            >
              <div class="AvatarBox">
                <el-image :src="item.image" class="friendAvatar"></el-image>
              </div>
              <div class="friendContent">
                <div class="username2">{{ item.name }}</div>
                <!-- <div class="content">{{item.content}}</div> -->
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="friendAndMessageList" v-if="listType === 2">
        <span class="FMTitle">Chat</span>
        <span class="subTitle">Message List</span>

        <div style="height: 560px; overflow: auto">
          <div v-for="(item, index) in messageList" :key="item">
            <div
              class="friendInfo"
              @click="transformChatMainMessage(item, index)"
            >
              <div class="AvatarBox">
                <el-image
                  :src="item.image"
                  class="friendAvatar"
                  style="left"
                ></el-image>
              </div>
              <div class="friendContent">
                <div class="username">{{ item.noteType }}</div>
                <div class="content">{{ item.title }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="friendAndMessageList" v-if="listType === 3">
        <span class="FMTitle">Chat</span>
        <span class="subTitle">Game List</span>

        <div style="height: 560px; overflow: auto">
          <div v-for="(item, index) in gameList" :key="item">
            <div
              class="friendInfo"
              @click="transformChatMainGame(index)"
              v-if="sendCount >= item.count"
            >
              <div class="AvatarBox">
                <el-image
                  :src="item.image"
                  class="friendAvatar"
                  style="left"
                ></el-image>
              </div>
              <div class="friendContent">
                <div class="username2">{{ item.name }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!--聊天界面-->
      <div class="" style="width: 68%; position: relative">
        <!--聊天默认界面-->
        <div class="flex flex-col" v-if="!transformChat">
          <el-image :src="avatar" class="chatAvatar"></el-image>
          <div style="margin-top: 4%; margin-left: 1%; font-weight: 600">
            Hey，{{ username }}！
          </div>
          <div style="margin-top: 1%; margin-left: 1%; font-weight: lighter">
            Please select a chat to start messaging.
          </div>
        </div>
        <div v-if="transformChat">
          <!--聊天界面表头-->
          <div class="" style="height: 80px; border-bottom: #21aa93 solid 1px">
            <el-image
              :src="topUserInfo.image"
              class="chatFriendAvatar"
              @click="toUserPersonal()"
            ></el-image>
            <div class="chatFriendName">{{ topUserInfo.name }}</div>
            <div class="chatFriendState">{{ topUserInfo.state }}</div>
            <div class="chatFriendInfo" v-if="listType === 1">
              <el-popconfirm
                title="你想要退出该群组吗"
                @confirm="exitGroup"
                confirm-button-text="确定"
                cancel-button-text="取消"
                cancel-button-type="danger"
              >
                <template #reference>
                  <el-image
                    :src="require('@/assets/chat/exit.png')"
                    class="chatFriendInfo_icon_add"
                    style="left: 90%; top: 30%"
                  ></el-image>
                </template>
              </el-popconfirm>
              <el-popconfirm
                title="请选择处理方式"
                v-for="(item, index) in topUserInfo.groupImageList"
                width="200px"
                @confirm="addGroupFriend(item)"
                @cancel="kickGroup(item, index)"
                :key="item"
                confirm-button-text="添加好友"
                cancel-button-text="踢出群组"
                cancel-button-type="danger"
              >
                <template #reference>
                  <el-image
                    :src="item.image"
                    class="chatFriendInfo_group"
                    :style="{ left: `${(index + 1) * 12}%`, top: `${20}%` }"
                  ></el-image>
                </template>
              </el-popconfirm>
            </div>
            <div class="chatFriendInfo" v-if="infoVisible">
              <el-popconfirm
                title="你想要和他建立好友关系吗？"
                @confirm="addFriend"
                @cancel="deleteFriend"
                v-if="sendCount >= 20"
                confirm-button-text="同意"
                cancel-button-text="拒绝"
                cancel-button-type="danger"
              >
                <template #reference>
                  <el-image
                    :src="require('@/assets/chat/add.png')"
                    class="chatFriendInfo_icon_add"
                    style="left: 1%; top: 30%"
                  ></el-image>
                </template>
              </el-popconfirm>
              <el-image
                :src="require('@/assets/chat/sex.png')"
                class="chatFriendInfo_icon"
                style="left: 13%; top: 30%"
                v-if="sendCount >= 5"
              ></el-image>
              <div
                class="chatFriendInfo_text"
                style="left: 19%; top: 30%"
                v-if="sendCount >= 5"
              >
                {{ topUserInfo.sex }}
              </div>
              <el-image
                :src="require('@/assets/chat/birthday.png')"
                class="chatFriendInfo_icon"
                style="left: 27%; top: 30%"
                v-if="sendCount >= 10"
              ></el-image>
              <div
                class="chatFriendInfo_text"
                style="left: 33%; top: 30%"
                v-if="sendCount >= 10"
              >
                {{ topUserInfo.birthday }}
              </div>
              <el-image
                :src="require('@/assets/chat/specialty.png')"
                class="chatFriendInfo_icon"
                style="left: 52%; top: 30%"
                v-if="sendCount >= 15"
              ></el-image>
              <div
                class="chatFriendInfo_text"
                style="left: 58%; top: 30%"
                v-if="sendCount >= 15"
              >
                {{ topUserInfo.major }}
              </div>
              <el-image
                :src="require('@/assets/chat/hobbies.png')"
                class="chatFriendInfo_icon"
                style="left: 77%; top: 30%"
                v-if="sendCount >= 20"
              ></el-image>
              <div
                class="chatFriendInfo_text"
                style="left: 83%; top: 30%"
                v-if="sendCount >= 20"
              >
                {{ topUserInfo.hobbies }}
              </div>
            </div>
          </div>
          <!--聊天记录-->
          <div
            class="infinite-list"
            style="overflow: auto; border-bottom: #21aa93 solid 1px"
            ref="main"
          >
            <div
              v-for="item in messageListChat"
              :key="item"
              ref="content"
              v-show="!videoObj.videoVisible"
            >
              <div class="chatBox" v-if="item.type === 0">
                <el-image :src="item.image" class="chatBox_Avatar"></el-image>
                <div class="chatBox_Message" v-if="testBlobUrl(item.content)">
                  <el-image
                    style="width: 150px; height: 150px"
                    :src="item.content"
                    v-if="testBlobUrl(item.content)"
                  />
                </div>
                <div v-else class="chatBox_Message">{{ item.content }}</div>
              </div>
              <div class="chatBox1" v-if="item.type === 1">
                <el-image :src="item.image" class="chatBox_Avatar1"></el-image>
                <div class="chatBox_Message1" v-if="testBlobUrl(item.content)">
                  <el-image
                    style="width: 150px; height: 150px"
                    :src="item.content"
                    v-if="testBlobUrl(item.content)"
                  />
                </div>
                <div v-else class="chatBox_Message1">{{ item.content }}</div>
              </div>
            </div>
            <!-- 视频聊天框 -->
            <div
              v-show="videoObj.videoVisible"
              style="display: flex; justify-content: space-between"
            >
              <video id="localVideo" class="localVideo"></video>
              <video id="remoteVideo" class="remoteVideo"></video>
            </div>
          </div>
          <!--发送框-->
          <div class="" style="height: 101px; position: relative">
            <div class="specialBox">
              <el-image
                class="emoPng"
                :src="require('@/assets/chat/emo.png')"
                @click="emoVisible = !emoVisible"
              />
              <div class="emoBox" v-if="emoVisible">
                <div
                  class="emojiChar"
                  v-for="emo in emoji"
                  :key="emo"
                  @click="sendEmo(emo)"
                >
                  {{ String.fromCodePoint(emo) }}
                </div>
              </div>
              <el-upload class="picPng" :http-request="picPngSendHandler">
                <el-image :src="require('@/assets/chat/pic.png')" />
              </el-upload>
              <el-image
                class="videoPng"
                :src="require('@/assets/chat/video.png')"
                @click="sendVideoReq"
              />
            </div>
            <textarea
              class="inputMessage"
              placeholder="请输入"
              style="height: 76px; top: 25px"
              v-model="sendMessage"
              type="textarea"
              @keydown="sendMsgHandler"
              @keyup="clear"
            />
          </div>
        </div>
      </div>
    </div>

    <el-dialog v-model="addFriendVisible" :title="addFriendMsg" width="30%">
      <span>你想要和他建立好友关系吗？</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="danger" @click="addGroupFriend_deal(0)"
            >拒绝</el-button
          >
          <el-button type="success" @click="addGroupFriend_deal(1)"
            >同意</el-button
          >
        </span>
      </template>
    </el-dialog>

    <el-dialog
      v-model="videoObj.videoDiaVisible"
      :title="videoObj.videoConfirm"
      width="30%"
    >
      <span>对方发来视频聊天请求，是否接受?</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="danger" @click="confirmVideo(0)">拒绝</el-button>
          <el-button type="success" @click="confirmVideo(1)">同意</el-button>
        </span>
      </template>
    </el-dialog>

    <!--游戏小弹窗-->

    <!--你画我猜-->
    <div class="black_overlay" v-show="drawGuessObj.drawGuessVisible">
      <div style="position: relative">
        <el-image
          class="game1"
          :src="require('@/assets/chat/game1.png')"
        ></el-image>
        <div class="drawGuessTitle" v-if="!drawGuessObj.isReceiver">
          {{ drawGuessObj.title }}
        </div>
        <div class="wraper" ref="wraper">
          <div
            class="canvas-wraper"
            :style="{
              'background-image': `url(${require('@/assets/001.jpg')})`,
            }"
            v-show="!drawGuessObj.isReceiver"
          >
            <canvas id="canvas" ref="canvas"></canvas>
          </div>
          <div class="controlPanel" v-if="!drawGuessObj.isReceiver">
            <div
              :class="[initIdx == idx ? 'contro-item active' : 'contro-item']"
              v-for="(item, idx) in toolsArr"
              :key="idx"
              @click="handleTools(item, idx)"
            >
              <i :class="'iconfont' + item.icon"></i>
            </div>
          </div>

          <!--接收方-->
          <el-image
            class="canvas-wraper2"
            :src="drawGuessObj.receivePic"
            v-if="drawGuessObj.isReceiver"
          ></el-image>
          <el-image
            class="canvas-wraper2"
            v-if="drawGuessObj.isReceiver && !drawGuessObj.receivePic"
            :src="require('@/assets/chat/default.png')"
          ></el-image>
        </div>
        <div
          class="flex flex-row justify-center"
          v-if="!drawGuessObj.isReceiver"
        >
          <el-button
            class="drawGuessSend"
            style="margin-right: 15%"
            type="primary"
            v-if="!drawGuessObj.isSend"
            @click="sendPic()"
            >发送图片</el-button
          >
          <el-input
            style="width: 10%; margin-right: 1%"
            v-model="drawGuessObj.sendGuessContent"
            v-if="drawGuessObj.isSend"
          ></el-input>
          <el-button
            style="width: 7%"
            type="success"
            v-if="drawGuessObj.isSend"
            @click="justifyAns(1)"
            >回答正确</el-button
          >
          <el-button
            style="width: 7%; margin-right: 10%"
            type="danger"
            v-if="drawGuessObj.isSend"
            @click="justifyAns(0)"
            >回答错误</el-button
          >
          <el-button
            class="drawGuessSend"
            type="warning"
            @click="exitDrawGuess()"
            >退出游戏</el-button
          >
        </div>

        <!--接收方-->
        <div
          class="flex flex-row justify-center"
          v-if="drawGuessObj.isReceiver"
        >
          <el-input
            style="width: 10%"
            v-model="drawGuessObj.receiveGuessContent"
          ></el-input>
          <el-button
            style="width: 5%"
            type="primary"
            @click="sendReceiveContent()"
            >发送</el-button
          >
          <el-button
            class="drawGuessSend"
            type="warning"
            @click="exitDrawGuess()"
            >退出游戏</el-button
          >
        </div>
      </div>
    </div>

    <el-dialog
      v-model="drawGuessObj.drawGuessConfirmVisible"
      :title="drawGuessObj.drawGuessConfirm"
      width="30%"
    >
      <span>你想要和对方一起进入你画我猜游戏吗</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="danger" @click="confirmDrawGuess(0)">拒绝</el-button>
          <el-button type="success" @click="confirmDrawGuess(1)"
            >同意</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!--真心话-->
    <div class="black_overlay" v-show="realThinkObj.realThinkVisible">
      <div
        class="realThinkBackGround"
        :style="{
          'background-image': `url(${require('@/assets/chat/trueTalkBackGround.png')})`,
        }"
      >
        <div class="realThinkQuestion">{{ realThinkObj.question }}</div>
        <el-input
          v-model="realThinkObj.myAns"
          class="realThinkInput"
          @click="sendRealThink()"
        >
          <template #prepend>你的答案：</template>
        </el-input>
        <el-input
          v-model="realThinkObj.anotherAns"
          class="realThinkInput"
          disabled
        >
          <template #prepend>对方答案：</template>
        </el-input>
        <div class="realThinkButton">
          <el-button
            class="realThinkButtonItem"
            type="success"
            @click="sendRealThink()"
            >发送</el-button
          >
          <el-button
            class="realThinkButtonItem"
            type="primary"
            @click="nextRealThink()"
            >下一题</el-button
          >
          <el-button
            class="realThinkButtonItem"
            type="warning"
            @click="exitRealThink()"
            >退出游戏</el-button
          >
        </div>
      </div>
    </div>

    <el-dialog
      v-model="realThinkObj.realThinkConfirmVisible"
      :title="realThinkObj.realThinkConfirm"
      width="30%"
    >
      <span>你想要和对方一起进入真心话游戏吗</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="danger" @click="confirmReal(0)">拒绝</el-button>
          <el-button type="success" @click="confirmReal(1)">同意</el-button>
        </span>
      </template>
    </el-dialog>

    <!--土味情话-->
    <div class="black_overlay" v-show="loveTalkObj.loveTalkVisible">
      <el-image
        class="game1"
        :src="require('@/assets/chat/game2.png')"
      ></el-image>
      <div class="flex flex-row justify-center">
        <div class="loveTalkCompete">
          <div class="flex flex-row" style="margin-bottom: 8%">
            <el-image :src="avatar" class="loveTalkMyAvatar"></el-image>
            <el-image
              :src="loveTalkObj.listImage[loveTalkObj.contest]"
              class="loveTalkGuess"
            ></el-image>
          </div>
          <div class="flex flex-row" style="margin-bottom: 8%">
            <el-image
              :src="topUserInfo.image"
              class="loveTalkMyAvatar"
            ></el-image>
            <el-image
              :src="loveTalkObj.listImage[loveTalkObj.contestAno]"
              class="loveTalkGuess"
            ></el-image>
          </div>
          <el-button
            style="width: 40%; border-radius: 50%; opacity: 0.8"
            type="success"
            @click="continueLoveTalk()"
            >继续</el-button
          >
          <el-button
            style="width: 40%; border-radius: 50%; opacity: 0.8"
            type="warning"
            @click="exitLoveTalk()"
            >退出游戏</el-button
          >
        </div>
        <div class="loveTalkChat">
          <div
            class="infinite-list"
            style="
              overflow: auto;
              border-bottom: #21aa93 solid 1px;
              height: 420px;
            "
            ref="main"
          >
            <div v-for="item in loveTalkObj.chatList" :key="item" ref="content">
              <div class="chatBox" v-if="item.type === 0">
                <el-image :src="item.image" class="chatBox_Avatar"></el-image>
                <div class="chatBox_Message">{{ item.content }}</div>
              </div>
              <div class="chatBox1" v-if="item.type === 1">
                <el-image :src="item.image" class="chatBox_Avatar1"></el-image>
                <div class="chatBox_Message1">{{ item.content }}</div>
              </div>
            </div>
          </div>
          <div style="height: 40px; position: relative">
            <textarea
              class="inputMessage"
              placeholder="请输入"
              v-model="loveTalkObj.myloveTalk"
              type="textarea"
              @keydown="sendloveTalk"
              @keyup="clearLoveTalk"
            />
          </div>
        </div>
        <div class="loveTalkTemplate" style="overflow: auto">
          <div
            v-for="item in loveTalkObj.loveTalkList"
            :key="item"
            style="
              border-bottom: #21aa93 solid 1px;
              margin-bottom: 5%;
              padding-bottom: 20px;
              padding-top: 20px;
              font-family: '楷体';
              font-size: 18px;
            "
          >
            <div
              class="flex justify-center tracking-wider"
              style="color: #fff"
              v-for="item2 in item.loveTalkList"
              :key="item2"
            >
              <div>{{ item2 }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <el-dialog
      v-model="loveTalkObj.loveTalkConfirmVisible"
      :title="loveTalkObj.loveTalkConfirm"
      width="30%"
    >
      <span>你想要和对方一起进入土味情话游戏吗</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="danger" @click="confirmLoveTalk(0)">拒绝</el-button>
          <el-button type="success" @click="confirmLoveTalk(1)">同意</el-button>
        </span>
      </template>
    </el-dialog>

    <!--接龙-->
    <div class="black_overlay" v-show="storyDragonObj.storyDragonVisible">
      <el-alert
        :title="storyDragonObj.alert"
        center
        show-icon
        type="info"
        style="margin-top: 0%"
      />
      <el-icon
        style="position: absolute; left: 84%"
        color="#fff"
        :size="30"
        @click="exitstoryDragon()"
        ><Close
      /></el-icon>
      <div
        class="storyDragonBackGround"
        :style="{
          'background-image': `url(${require('@/assets/chat/storyDragonBackground.png')})`,
        }"
      >
        <div
          style="
            color: #fff;
            margin: auto;
            width: 600px;
            font-size: 35px;
            font-family: '隶书';
          "
        >
          {{ storyDragonObj.storyStart }}
        </div>
      </div>
      <div
        class="storyDragonChat"
        style="overflow: auto; border-bottom: #21aa93 solid 1px; height: 140px"
      >
        <div v-for="item in storyDragonObj.listChat" :key="item" ref="content">
          <div class="chatBox" v-if="item.type === 0">
            <el-image :src="item.image" class="chatBox_Avatar"></el-image>
            <div class="chatBox_Message">{{ item.content }}</div>
          </div>
          <div class="chatBox1" v-if="item.type === 1">
            <el-image :src="item.image" class="chatBox_Avatar1"></el-image>
            <div class="chatBox_Message1">{{ item.content }}</div>
          </div>
        </div>
      </div>
      <div style="width: 960px; height: 40px; margin: auto; position: relative">
        <textarea
          class="inputMessage"
          placeholder="请输入"
          v-model="storyDragonObj.myStory"
          type="textarea"
          @keydown="sendStory"
          @keyup="clearStory"
        />
      </div>
    </div>

    <el-dialog
      v-model="storyDragonObj.storyDragonConfirmVisible"
      :title="storyDragonObj.storyDragonConfirm"
      width="30%"
    >
      <span>你想要和对方一起进入故事接龙游戏吗</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="danger" @click="confirmStoryDragon(0)"
            >拒绝</el-button
          >
          <el-button type="success" @click="confirmStoryDragon(1)"
            >同意</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { fabric } from "fabric";
import sport from "@/assets/chat/sport.png";
import love from "@/assets/chat/love.png";
import game from "@/assets/chat/game.png";
import study from "@/assets/chat/study.png";
import competition from "@/assets/chat/competition.png";
import eat from "@/assets/chat/eat.png";
import thinking from "@/assets/chat/thinking.png";
import chatAPI from "@/api/chatAPI";
import scriptAPI from "@/api/scriptAPI";
import loginAPI from "@/api/loginAPI";
import commonAPI from "@/api/commonAPI";
import draw from "@/assets/chat/draw.png";
import trueTalk from "@/assets/chat/trueTalk.png";
import tuwei from "@/assets/chat/tuwei.png";
import jielong from "@/assets/chat/jielong.png";
import { loveTalk } from "./loveTalk";
import guess0 from "@/assets/chat/guess0.png";
import guess1 from "@/assets/chat/guess1.png";
import guess2 from "@/assets/chat/guess2.png";
import guess3 from "@/assets/chat/guess3.png";
import { emoji } from "./emoji";
export default {
  data() {
    return {
      //表情包
      emoji: emoji,

      emoVisible: false,

      videoObj: {
        videoDiaVisible: false,
        videoConfirm: "",
        isReceiver: true,
        videoVisible: false,
        localPeer: {},
        remotePeer: {},
        localStream: {},
        remoteStream: {},
        remoteOffer: {},
        localOffer: {},
        localCandidate: {},
        remoteCandidate: {},
      },

      //你画我猜需要用到的变量
      drawGuessObj: {
        drawGuessVisible: false,
        isReceiver: true,
        isSend: false,
        receivePic: "",
        receiveGuessContent: "",
        sendGuessContent: "",
        icon: "",
        title: "",
        drawGuessConfirmVisible: false,
        drawGuessConfirm: "",
      },

      //真心话需要用到的变量
      realThinkObj: {
        realThinkVisible: false,
        question: "你谈过几次恋爱",
        myAns: "",
        anotherAns: "",
        realThinkConfirmVisible: false,
        realThinkConfirm: "",
      },

      //土味情话需要用到的变量
      loveTalkObj: {
        loveTalkVisible: false,
        loveTalkConfirmVisible: false,
        loveTalkConfirm: "",
        contest: 3, //剪刀石头布 0,1,2
        contestAno: 3,
        list: ["剪刀", "石头", "布", ""],
        listImage: [guess0, guess1, guess2, guess3],
        canSend: false,
        //到时候改成对话列表的形式
        myloveTalk: "",
        receiveLoveTalk: "",
        loveTalkList: loveTalk,
        sendloveTalk: "",
        chatList: [],
      },

      //故事接龙需要用到的变量
      storyDragonObj: {
        storyDragonVisible: false,
        storyStart: "从前有座山山上有个老人和小和尚",
        myStory: "",
        anoStory: "",
        storyDragonConfirmVisible: false,
        storyDragonConfirm: "",
        isSend: false,
        alert:
          "故事接龙：聊天双方轮流为平台随机给出的开头续接一个句子，由发起方开始",
        listChat: [],
      },

      count: 2,

      value: "",

      sendMessage: "",

      infoVisible: false,

      addFriendVisible: false,

      //申请添加好友的信息
      addFriendMsg: "",

      //申请添加好友id
      addFriendId: "",

      transformChat: false,

      username: this.$store.getters["user/getUserName"],

      listType: 2,

      avatar: this.$store.getters["user/getUserAvatar"],

      //是否建立连接
      isConnect: false,

      topUserInfo: {
        state: "",
        image: "",
        name: "",
        id: "",
        sex: "",
        birthday: "",
        major: "",
        hobbies: "",
        index: "",
        groupImageList: [],
        publisherId: "",
        userId: "",
      },

      userList: [],

      groupList: [],

      //记录消息条数
      sendCount: 0,

      messageList: [],

      gameList: [
        {
          image: draw,
          name: "你画我猜",
          count: 5,
        },
        {
          image: trueTalk,
          name: "真心话",
          count: 10,
        },
        {
          image: tuwei,
          name: "土味情话",
          count: 15,
        },
        {
          image: jielong,
          name: "故事接龙",
          count: 20,
        },
      ],

      messageListChat: [],

      scriptTypeList: [
        "运动",
        "恋爱",
        "游戏",
        "学习",
        "竞赛",
        "约饭",
        "奇思妙想",
      ],

      messageImage: [sport, love, game, study, competition, eat, thinking],

      //是否正在输入
      isInputing: false,

      groupUserAvatar: "",

      currentTool: "",

      done: false,
      fabricObj: null,
      initIdx: 0,
      toolsArr: [
        {
          name: "pencil",
          icon: " icon-pencil",
        },
        {
          name: "line",
          icon: " icon-line",
        },
        {
          name: "arrow",
          icon: " icon-arrow",
        },
        {
          name: "dashedline",
          icon: " icon-xuxian",
        },
        {
          name: "rectangle",
          icon: " icon-juxing",
        },
        {
          name: "circle",
          icon: " icon-yuanxing",
        },
        {
          name: "ellipse",
          icon: " icon-tuoyuanxing",
        },
        {
          name: "equilateral", //三角形
          icon: " icon-sanjiaoxing",
        },
        {
          name: "remove",
          icon: " icon-remove",
        },
        {
          name: "reset",
          icon: " icon-reset",
        },
      ],
      mouseFrom: {},
      mouseTo: {},
      moveCount: 1,
      doDrawing: false,
      fabricHistoryJson: [],
      mods: 0,
      drawingObject: null, //绘制对象
      drawColor: "#E34F51",
      drawWidth: 2,
      imageBase64: "",
      zoom: window.zoom ? window.zoom : 1,
    };
  },

  created() {
    this.getMessageListInfo();
    this.messageListChat = [];
    this.$socket.registerCallBack(this.testData);
  },

  destroyed() {
    // 取消回调函数
    this.$socket.unRegisterCallBack(this.testData);
  },

  watch: {
    listType(newListType, oldListType) {
      if (newListType !== 3) {
        this.transformChat = false;
        if (oldListType === 2) {
          this.sendMessageCount(this.topUserInfo.id);
        }
        this.listTypeChange(oldListType);
        this.messageListChat = [];
      }
    },

    transformChat: {
      handler(newTransformChat) {
        if (newTransformChat === false) {
          this.sendMessageCount(this.topUserInfo.id);
        }
      },
      deep: true,
    },

    sendCount: {
      handler(newvalue) {
        console.log(newvalue);
      },
      deep: true,
    },
  },

  computed: {
    canvasWidth() {
      return window.innerWidth;
    },
  },

  mounted() {
    this.initCanvas();
  },

  methods: {
    /**
     * @description 建立好友
     */
    async addFriend() {
      let data = {
        noteId: this.topUserInfo.id,
      };
      await chatAPI.setFriend(data).then((res) => {
        console.log(res);
        this.$message.warning("等待对方确认");
      });
    },

    /**
     * @description 拒绝建立好友
     */
    async deleteFriend() {
      let data = {
        noteId: this.topUserInfo.id,
      };
      await chatAPI.refuseFriend(data).then((res) => {
        console.log(res);
      });
    },

    /**
     * @description 退出群组
     * @method refreshGroupList 刷新群组列表
     */
    async exitGroup() {
      let data = {
        noteId: this.topUserInfo.id,
      };
      await chatAPI.exitGroup(data).then((res) => {
        console.log(res);
        this.$message.success("退群成功");
        this.transformChat = false;
        this.refreshGroupList();
      });
    },

    /**
     * @description 踢出群组
     */
    async kickGroup(data, index) {
      if (
        this.topUserInfo.publisherId === this.$store.getters["user/getUserId"]
      ) {
        let data1 = {
          userId: data.userId,
          noteId: this.topUserInfo.id,
        };
        console.log(data1);
        await chatAPI.kickGroup(data1).then((res) => {
          console.log(res);
          this.$message.success("成功踢出该用户");
          console.log(index);
          this.topUserInfo.groupImageList.splice(index, 1);
          this.topUserInfo.state =
            this.topUserInfo.groupImageList.length + 1 + "人";
          this.groupList[this.topUserInfo.index].imageList =
            this.topUserInfo.groupImageList;
        });
      } else {
        this.$message.warning("对不起，只有群主具有踢人的权限");
      }
    },

    /**
     * @description 群聊中建立好友关系
     * @method getFriendList 刷新好友列表
     * @method addGroupFriend_deal 同意或者拒绝
     */
    async addGroupFriend(data) {
      if (
        data.userId === this.topUserInfo.publisherId ||
        this.$store.getters["user/getUserId"] === this.topUserInfo.publisherId
      ) {
        let data1 = {
          friendId: data.userId,
        };
        await chatAPI.groupAddFriend(data1).then((res) => {
          console.log(res);
          this.$message.success("好友申请已经发出");
          this.getFriendList();
        });
      }
    },

    async getFriendList() {
      this.userList = [];
      //获取好友列表
      await chatAPI.getFriends().then((res) => {
        console.log(res);
        if (res.code === 1) {
          res.data.forEach((item) => {
            this.getFriendInfo(item.friendId);
          });
        }
      });
    },

    async addGroupFriend_deal(accept) {
      let data1 = {
        friendId: this.addFriendId,
        accept: accept,
      };
      await chatAPI.groupAddFriend_deal(data1).then((res) => {
        console.log(res);
        this.addFriendVisible = false;
      });
    },

    async refreshGroupList() {
      this.groupList = [];
      await chatAPI.getPersonalGroup().then((res) => {
        console.log(res);
        res.data.forEach((item, index) => {
          this.getGroupList(item, index);
        });
      });
    },

    /**
     * @description 当listType切换时初始化数据
     */
    listTypeChange(type) {
      if (type === 2 && this.topUserInfo.index !== "") {
        this.messageList[this.topUserInfo.index].messages =
          this.messageListChat;
        this.messageList[this.topUserInfo.index].messageCount = this.sendCount;
      }
      if (type === 1 && this.topUserInfo.index !== "") {
        this.groupList[this.topUserInfo.index].messages = this.messageListChat;
      }
      if (type === 0 && this.topUserInfo.index !== "") {
        this.userList[this.topUserInfo.index].messages = this.messageListChat;
      }
      this.topUserInfo = {
        state: "",
        image: "",
        name: "",
        id: "",
        sex: "",
        birthday: "",
        major: "",
        hobbies: "",
        index: "",
        groupImageList: "", //群组列表可以用
        publisherId: "", //群组专用
      };
    },

    toMain() {
      this.$router.push("/main");
    },

    /**
     * @description 点击头像logo转换到主界面
     */
    transformMain() {
      this.transformChat = false;
    },

    /**
     * @description 点击消息列表不同成员
     * @method transformChatMainMessage_auxiliaryMethod1 当点击另一个消息时的处理函数
     * @method transformChatMainMessage_auxiliaryMethod2 将topUserInfo刷新
     * @method sendMessageCount 传递发送消息条数（通过noteId识别）
     */
    transformChatMainMessage(data, index) {
      console.log(data);
      this.transformChat = true;
      if (this.topUserInfo.id !== data.id && this.topUserInfo.id !== "") {
        this.transformChatMainMessage_auxiliaryMethod1(
          this.topUserInfo.index,
          index
        );
      }
      this.transformChatMainMessage_auxiliaryMethod2(data, index);
    },

    transformChatMainMessage_auxiliaryMethod1(oldIndex, newIndex) {
      this.sendMessageCount(this.topUserInfo.id);
      this.messageList[oldIndex].messages = this.messageListChat;
      this.messageList[oldIndex].messageCount = this.sendCount;
      this.messageListChat = this.messageList[newIndex].messages;
    },

    async transformChatMainMessage_auxiliaryMethod2(data, newIndex) {
      this.sendCount = data.messageCount;
      this.topUserInfo.name = data.noteType;
      this.topUserInfo.state = data.title;
      this.topUserInfo.image = data.image;
      this.topUserInfo.id = data.id;
      this.topUserInfo.index = newIndex;
      this.infoVisible = true;
      console.log(data);
      if (data.privateChat) {
        await chatAPI.getNoteUser(this.topUserInfo.id).then((res) => {
          console.log(res);
          this.topUserInfo.sex = res.data.sex;
          this.topUserInfo.birthday = res.data.birthday;
          this.topUserInfo.major = res.data.major;
          this.topUserInfo.hobbies = res.data.hobbies;
          this.topUserInfo.userId = res.data.id;
        });
      }
    },

    async sendMessageCount(id) {
      let data = {
        noteId: id,
        messageCount: this.sendCount,
      };
      console.log(data);
      await chatAPI.sendMessageNumber(data).then((res) => {
        console.log(res);
      });
    },

    /**
     * @description 点击群组列表不同成员
     * @method transformChatMainGroup_auxiliary1 当切换另一个群组聊天
     * @method transformChatMainGroup_auxiliary2 将topUserInfo刷新
     */
    transformChatMainGroup(data, index) {
      this.transformChat = true;
      this.infoVisible = false;
      if (this.topUserInfo.id !== data.id && this.topUserInfo.id !== "") {
        this.transformChatMainGroup_auxiliary1(this.topUserInfo.index, index);
      }
      this.transformChatMainGroup_auxiliary2(data, index);
    },

    transformChatMainGroup_auxiliary1(oldIndex, newIndex) {
      this.groupList[oldIndex].messages = this.messageListChat;
      this.messageListChat = this.groupList[newIndex].messages;
    },

    transformChatMainGroup_auxiliary2(data, index) {
      this.topUserInfo.name = data.name;
      this.topUserInfo.image = data.image;
      this.topUserInfo.id = data.id;
      this.topUserInfo.index = index;
      this.topUserInfo.state = data.imageList.length + 1 + "人";
      this.topUserInfo.groupImageList = data.imageList;
      this.topUserInfo.publisherId = data.publisherId;
    },

    /**
     * @description 点击好友列表不同好友
     * @method transformChatMainFriend_auxiliary1 当切换另一个好友聊天
     * @method transformChatMainFriend_auxiliary2 将topUserInfo刷新
     * @method getState 获取对方状态离线或者在线(通过用户id识别)
     */
    transformChatMainFriend(data, index) {
      this.transformChat = true;
      this.infoVisible = false;
      if (this.topUserInfo.id !== data.id && this.topUserInfo.id !== "") {
        this.transformChatMainFriend_auxiliary1(this.topUserInfo.index, index);
      }
      this.transformChatMainFriend_auxiliary2(data, index);
    },

    transformChatMainFriend_auxiliary1(oldIndex, newIndex) {
      console.log(oldIndex);
      this.userList[oldIndex].messages = this.messageListChat;
      this.messageListChat = this.userList[newIndex].messages;
    },

    transformChatMainFriend_auxiliary2(data, index) {
      this.topUserInfo.name = data.name;
      this.topUserInfo.image = data.image;
      this.topUserInfo.id = data.id;
      this.topUserInfo.index = index;
      this.getState(data.id);
    },

    async getState(id) {
      await loginAPI.getState(id).then((res) => {
        console.log(res);
        this.topUserInfo.state = res.data === true ? "在线" : "离线";
      });
    },

    /**
     * @description 点击不同游戏处理函数
     *
     * 你画我猜函数
     * @method initialDrawGuess 清空相关变量
     * @method drawAndGuess 你画我猜处理函数
     * @method confirmDrawGuess 建立联系
     * @method sendPic 绘图方发送图片函数
     * @method sendPic_messageType 发送图片时向websocket发送消息
     * @method sendReceiveContent 发送接收者这边的猜测内容
     * @method justifyAns 回答正确与否
     * @method exitDrawGuess 退出你画我猜游戏
     *
     * 真心话函数
     * @method initialRealThink 初始化
     * @method realThinkFun 真心话处理函数
     * @method confirmReal 同意或者拒绝对方的真心话邀请
     * @method sendRealThink 发送自己的答案
     * @method exitRealThink 退出真心话
     * @method nextRealThink 下一题真心话
     *
     * 土味情话函数
     * @method loveTalkFun 土味情话处理函数
     * @method confirmLoveTalk 同意或者拒绝对方的土味情话邀约
     * @method justifyContest 判断双方猜拳结果
     * @method deuce 平局处理
     * @method sendloveTalk 发送土味情话
     * @method exitLoveTalk 退出土味情话
     * @method continueLoveTalk 继续土味情话
     * @method clearLoveTalk 清楚土味情话输入框
     *
     * 故事接龙函数
     * @method storyDragonFun 故事接龙处理函数
     * @method confirmStoryDragon 同意或者拒绝对方的故事接龙邀约
     * @method sendStory 发送故事
     * @method exitstoryDragon 退出故事接龙
     */
    transformChatMainGame(index) {
      if (index === 0) {
        this.drawAndGuess();
      } else if (index === 1) {
        this.realThinkFun();
      } else if (index === 2) {
        this.loveTalkFun();
      } else {
        this.storyDragonFun();
      }
    },

    //<!-------------------------------  你画我猜  ------------------------------>
    initialDrawGuess() {
      this.drawGuessObj.receivePic = "";
      this.receiveGuessContent = "";
      this.sendGuessContent = "";
    },

    confirmDrawGuess(type) {
      if (type === 1) {
        this.drawGuessObj.drawGuessVisible = true;
        this.drawGuessObj.drawGuessConfirmVisible = false;
        let data = {
          messageType: 13,
          fromUser: this.$store.getters["user/getUserId"],
          toUser: this.topUserInfo.userId,
          gameCategory: 0,
        };
        this.$socket.send(JSON.stringify(data));
        this.$message.success("好的，现在你们可以进行你画我猜游戏了");
      } else {
        this.drawGuessObj.drawGuessConfirmVisible = false;
        let data = {
          noteId: null,
          messageType: 14,
          fromUser: this.$store.getters["user/getUserId"],
          toUser: this.topUserInfo.userId,
          gameCategory: 0,
        };
        this.$socket.send(JSON.stringify(data));
      }
    },

    drawAndGuess() {
      this.drawGuessObj.drawGuessVisible = true;
      this.drawGuessObj.isReceiver = false;
      let data = {
        messageType: 12,
        fromUser: this.$store.getters["user/getUserId"],
        toUser: this.topUserInfo.userId,
        gameCategory: 0,
        msg:
          "收到" + this.$store.getters["user/getUserName"] + "你画我猜游戏申请",
      };
      console.log(data);
      this.$socket.send(JSON.stringify(data));
    },

    async sendPic() {
      //生成双倍像素比的图片
      let base64URl = this.fabricObj.toDataURL({
        formart: "png",
        multiplier: 2,
      });
      this.imageBase64 = base64URl;
      this.done = false;

      var bytes = window.atob(base64URl.split(",")[1]);

      var array = [];
      for (var i = 0; i < bytes.length; i++) {
        array.push(bytes.charCodeAt(i));
      }
      var blob = new Blob([new Uint8Array(array)], { type: "image/png" });
      var fd = new FormData();
      fd.append("file", blob, Date.now() + ".png");

      await commonAPI.upload(fd).then((res) => {
        if (res.code === 1) {
          this.$message.success("发送成功，请等待对方消息");
          this.drawGuessObj.isSend = true;
          this.drawGuessObj.icon = res.data;
          this.sendPic_messageType(this.drawGuessObj.icon);
        }
      });
    },

    sendPic_messageType(icon) {
      let data = {
        messageType: 18,
        fromUser: this.$store.getters["user/getUserId"],
        toUser: this.topUserInfo.userId,
        msg: icon,
      };
      this.$socket.send(JSON.stringify(data));
    },

    sendReceiveContent() {
      let data = {
        messageType: 16,
        fromUser: this.$store.getters["user/getUserId"],
        toUser: this.topUserInfo.userId,
        gameCategory: 0,
        msg: this.drawGuessObj.receiveGuessContent,
      };
      this.$socket.send(JSON.stringify(data));
    },

    justifyAns(type) {
      let msgSend = type === 1 ? "success" : "refuse";
      let data = {
        messageType: 16,
        fromUser: this.$store.getters["user/getUserId"],
        toUser: this.topUserInfo.userId,
        gameCategory: 0,
        msg: msgSend,
      };
      this.$socket.send(JSON.stringify(data));
      this.drawGuessObj.isReceiver = true;
      this.initialDrawGuess();
    },

    exitDrawGuess() {
      this.drawGuessObj.drawGuessVisible = false;
      this.drawGuessObj.isReceiver = true;
      this.drawGuessObj.isSend = false;
      this.initialDrawGuess();
      let data = {
        messageType: 15,
        fromUser: this.$store.getters["user/getUserId"],
        toUser: this.topUserInfo.userId,
        gameCategory: 0,
      };
      this.$socket.send(JSON.stringify(data));
    },

    //<!-------------------------------  真心话  ------------------------------>
    initialRealThink() {
      this.realThinkObj.question = "";
      this.realThinkObj.myAns = "";
      this.realThinkObj.anotherAns = "";
    },

    realThinkFun() {
      this.realThinkObj.realThinkVisible = true;
      let data = {
        messageType: 12,
        fromUser: this.$store.getters["user/getUserId"],
        toUser: this.topUserInfo.userId,
        gameCategory: 1,
        msg:
          "收到" + this.$store.getters["user/getUserName"] + "真心话游戏申请",
      };
      this.$socket.send(JSON.stringify(data));
    },

    confirmReal(type) {
      if (type === 1) {
        this.realThinkObj.realThinkVisible = true;
        this.realThinkObj.realThinkConfirmVisible = false;
        let data = {
          messageType: 13,
          fromUser: this.$store.getters["user/getUserId"],
          toUser: this.topUserInfo.userId,
          gameCategory: 1,
        };
        this.$socket.send(JSON.stringify(data));
        this.$message.success("好的，现在你们可以真心话游戏了");
      } else {
        this.realThinkObj.realThinkConfirmVisible = false;
        let data = {
          messageType: 14,
          fromUser: this.$store.getters["user/getUserId"],
          toUser: this.topUserInfo.userId,
          gameCategory: 1,
        };
        this.$socket.send(JSON.stringify(data));
      }
    },

    sendRealThink() {
      let data = {
        messageType: 16,
        fromUser: this.$store.getters["user/getUserId"],
        toUser: this.topUserInfo.userId,
        gameCategory: 1,
        msg: this.realThinkObj.myAns,
      };
      this.$socket.send(JSON.stringify(data));
    },

    exitRealThink() {
      this.realThinkObj.realThinkVisible = false;
      let data = {
        messageType: 15,
        fromUser: this.$store.getters["user/getUserId"],
        toUser: this.topUserInfo.userId,
        gameCategory: 1,
      };
      this.$socket.send(JSON.stringify(data));
    },

    nextRealThink() {
      let data = {
        messageType: 17,
        fromUser: this.$store.getters["user/getUserId"],
        toUser: this.topUserInfo.userId,
        gameCategory: 1,
      };
      this.$socket.send(JSON.stringify(data));
    },

    //<!-------------------------------  土味情话  ------------------------------>
    loveTalkFun() {
      this.loveTalkObj.loveTalkVisible = true;
      this.loveTalkObj.chatList = [];
      let data = {
        messageType: 12,
        fromUser: this.$store.getters["user/getUserId"],
        toUser: this.topUserInfo.userId,
        gameCategory: 2,
        msg:
          "收到" + this.$store.getters["user/getUserName"] + "土味情话游戏申请",
      };
      this.$socket.send(JSON.stringify(data));
    },

    continueLoveTalk() {
      this.loveTalkObj.contest = Math.round(Math.random() * 2);
      let data = {
        messageType: 19,
        fromUser: this.$store.getters["user/getUserId"],
        toUser: this.topUserInfo.userId,
        gameCategory: 2,
        msg: this.loveTalkObj.contest,
      };
      this.$socket.send(JSON.stringify(data));
    },

    confirmLoveTalk(type) {
      if (type === 1) {
        this.loveTalkObj.loveTalkVisible = true;
        this.loveTalkObj.loveTalkConfirmVisible = false;
        let data = {
          messageType: 13,
          fromUser: this.$store.getters["user/getUserId"],
          toUser: this.topUserInfo.userId,
          gameCategory: 2,
          msg: "",
        };
        this.$socket.send(JSON.stringify(data));
        this.$message.success("好的，现在你们可以进行土味情话游戏了");
        this.loveTalkObj.contest = Math.round(Math.random() * 2);

        //对data进行处理
        data.messageType = 16;
        data.msg = this.loveTalkObj.contest;
        this.$socket.send(JSON.stringify(data));
      } else {
        this.loveTalkObj.loveTalkConfirmVisible = false;
        let data = {
          messageType: 14,
          fromUser: this.$store.getters["user/getUserId"],
          toUser: this.topUserInfo.userId,
          gameCategory: 2,
        };
        this.$socket.send(JSON.stringify(data));
      }
    },

    deuce() {
      this.loveTalkObj.contest = Math.round(Math.random() * 2);
      let data = {
        messageType: 16,
        fromUser: this.$store.getters["user/getUserId"],
        toUser: this.topUserInfo.userId,
        gameCategory: 2,
        msg: this.loveTalkObj.contest,
      };
      this.$socket.send(JSON.stringify(data));
    },

    justifyContest() {
      if (this.loveTalkObj.contest === this.loveTalkObj.contestAno) {
        this.deuce();
      }
      if (this.loveTalkObj.contest === 0 && this.loveTalkObj.contestAno === 1)
        return true;
      if (this.loveTalkObj.contest === 0 && this.loveTalkObj.contestAno === 2)
        return false;
      if (this.loveTalkObj.contest === 1 && this.loveTalkObj.contestAno === 2)
        return true;
      if (this.loveTalkObj.contest === 1 && this.loveTalkObj.contestAno === 0)
        return false;
      if (this.loveTalkObj.contest === 2 && this.loveTalkObj.contestAno === 0)
        return true;
      if (this.loveTalkObj.contest === 2 && this.loveTalkObj.contestAno === 1)
        return false;
    },

    sendloveTalk(e) {
      this.isInputing = true;
      if (e.keyCode === 13) {
        let data = {
          messageType: 16,
          fromUser: this.$store.getters["user/getUserId"],
          toUser: this.topUserInfo.userId,
          gameCategory: 2,
          msg: this.loveTalkObj.myloveTalk,
        };
        let data1 = {
          type: 1,
          image: this.avatar,
          content: this.loveTalkObj.myloveTalk,
        };
        this.loveTalkObj.chatList.push(data1);
        this.$socket.send(JSON.stringify(data));
      }
    },

    clearLoveTalk(e) {
      if (e.keyCode === 13) {
        this.loveTalkObj.myloveTalk = "";
        this.isInputing = false;
      }
    },

    exitLoveTalk() {
      this.loveTalkObj.loveTalkVisible = false;
      let data = {
        messageType: 15,
        fromUser: this.$store.getters["user/getUserId"],
        toUser: this.topUserInfo.userId,
        gameCategory: 2,
      };
      this.$socket.send(JSON.stringify(data));
    },

    //<!-------------------------------  故事接龙  ------------------------------>
    storyDragonFun() {
      this.storyDragonObj.storyDragonVisible = true;
      // this.storyDragonObj.listChat = [];
      let data = {
        messageType: 12,
        fromUser: this.$store.getters["user/getUserId"],
        toUser: this.topUserInfo.userId,
        gameCategory: 3,
        msg:
          "收到" + this.$store.getters["user/getUserName"] + "土味情话游戏申请",
      };
      this.$socket.send(JSON.stringify(data));
    },

    confirmStoryDragon(type) {
      if (type === 1) {
        this.storyDragonObj.storyDragonVisible = true;
        this.storyDragonObj.storyDragonConfirmVisible = false;
        let data = {
          messageType: 13,
          fromUser: this.$store.getters["user/getUserId"],
          toUser: this.topUserInfo.userId,
          gameCategory: 3,
        };
        this.$socket.send(JSON.stringify(data));
        this.$message.success(
          "好的，现在你们可以进行故事接龙游戏了,由对方先开始"
        );
        this.storyDragonObj.isSend = false;
      } else {
        this.storyDragonObj.storyDragonConfirmVisible = false;
        let data = {
          messageType: 14,
          fromUser: this.$store.getters["user/getUserId"],
          toUser: this.topUserInfo.userId,
          gameCategory: 3,
        };
        this.$socket.send(JSON.stringify(data));
      }
    },

    sendStory(e) {
      this.isInputing = true;
      if (e.keyCode === 13) {
        let data = {
          messageType: 16,
          fromUser: this.$store.getters["user/getUserId"],
          toUser: this.topUserInfo.userId,
          gameCategory: 3,
          msg: this.storyDragonObj.myStory,
        };
        let data1 = {
          type: 1,
          image: this.avatar,
          content: this.storyDragonObj.myStory,
        };
        this.storyDragonObj.listChat.push(data1);
        this.storyDragonObj.isSend = false;
        this.$socket.send(JSON.stringify(data));
      }
    },

    clearStory(e) {
      if (e.keyCode === 13) {
        this.storyDragonObj.myStory = "";
        this.isInputing = false;
      }
    },

    exitstoryDragon() {
      this.storyDragonObj.storyDragonVisible = false;
      let data = {
        messageType: 15,
        fromUser: this.$store.getters["user/getUserId"],
        toUser: this.topUserInfo.userId,
        gameCategory: 3,
      };
      this.$socket.send(JSON.stringify(data));
    },

    /**
     * @description 获取好友列表相关
     */
    async getFriendListInfo() {
      this.listType = 0;
      this.userList = [];
      let list = await chatAPI.getFriends();
      list.data.forEach(async (item) => {
        // 获取朋友详细信息
        let data = await loginAPI.getUserInfo(item.friendId);
        let friend = {
          id: item.friendId,
          name: data.data.name,
          icon: data.data.icon,
          image: "",
          state: "离线",
          messages: [],
        };

        // 拿到好友头像
        let iconBlob = await commonAPI.download(friend.icon);
        let binaryData = [];
        binaryData.push(iconBlob);
        friend.image = window.URL.createObjectURL(new Blob(binaryData));

        this.userList.push(friend);
      });
    },

    /**
     * @description 获取群组列表相关
     */
    async getGroupListInfo() {
      this.listType = 1;
      this.groupList = [];
      let list = await chatAPI.getPersonalGroup();
      list.data.forEach(async (item) => {
        let group = {
          image: this.messageImage[Number(item.columnId)],
          name: item.name,
          imageList: [],
          id: item.noteId,
          messages: [],
          publisherId: item.publisherId,
        };
        // 获取群组成员详细信息
        let users = await chatAPI.getGroupUsers(item.noteId);
        users.data.forEach(async (user) => {
          let iconBlob = await commonAPI.download(user.icon);
          let binaryData = [];
          binaryData.push(iconBlob);
          let data = {
            userId: user.id,
            image: window.URL.createObjectURL(new Blob(binaryData)),
          };
          if (user.id !== this.$store.getters["user/getUserId"]) {
            group.imageList.push(data);
          }
        });

        this.groupList.push(group);
      });
    },

    /**
     * @description 获取匿名消息列表相关
     */
    async getMessageListInfo() {
      this.listType = 2;
      this.messageList = [];
      let list = await chatAPI.getTemporaryMsg();
      list.data.forEach(async (item) => {
        let data = await scriptAPI.getScriptInfo(item.noteId);
        let note = {
          title: data.data.title,
          noteType: this.scriptTypeList[Number(data.data.columnId)],
          id: item.noteId,
          privateChat: data.data.privateChat,
          image: this.messageImage[Number(data.data.columnId)],
          messageCount: item.messageCount,
          messages: [],
        };
        this.messageList.push(note);
      });
    },

    /**
     * @description 发送消息
     */
    async sendMsgHandler(e) {
      this.isInputing = true;
      if (e.keyCode === 13) {
        let data = {
          noteId: null,
          messageType: null,
          fromUser: this.$store.getters["user/getUserId"],
          toUser: null,
          fromGroup: null,
          toGroup: null,
          msg: this.sendMessage,
        };
        if (this.listType === 0) {
          data.messageType = 1;
          data.toUser = this.topUserInfo.id;
        }
        if (this.listType === 1) {
          data.messageType = 2;
          data.toGroup = this.topUserInfo.id;
          data.messageType = 2;
        }
        if (this.listType === 2 || this.listType === 3) {
          data.messageType = 3;
          data.noteId = this.topUserInfo.id;
        }
        console.log(data);
        this.$socket.send(JSON.stringify(data));
        let data1 = {
          type: 1,
          content: this.sendMessage,
          image: this.avatar,
        };
        if (this.sendMessage !== "") {
          await this.messageListChat.push(data1);
          this.$refs.main.scrollTop = this.$refs.main.scrollHeight;
        }
      }
    },

    /**
     * @description 回车清除发消息框内容
     */
    clear(e) {
      if (e.keyCode === 13) {
        this.sendMessage = "";
        this.sendCount++;
        this.isInputing = false;
      }
    },

    /**
     * @description 发送emo表情
     */
    async sendEmo(emo) {
      this.emoVisible = false;
      let data = {
        noteId: null,
        messageType: null,
        fromUser: this.$store.getters["user/getUserId"],
        toUser: null,
        fromGroup: null,
        toGroup: null,
        msg: emo,
      };
      if (this.listType === 0) {
        data.messageType = 1;
        data.toUser = this.topUserInfo.id;
      }
      if (this.listType === 1) {
        data.messageType = 2;
        data.toGroup = this.topUserInfo.id;
        data.messageType = 2;
      }
      if (this.listType === 2 || this.listType === 3) {
        data.messageType = 3;
        data.noteId = this.topUserInfo.id;
      }
      console.log(data);
      this.$socket.send(JSON.stringify(data));
      let data1 = {
        type: 1,
        content: String.fromCodePoint(emo),
        image: this.avatar,
      };
      this.sendCount++;
      await this.messageListChat.push(data1);
      this.$refs.main.scrollTop = this.$refs.main.scrollHeight;
    },

    /**
     * @description 聊天发送图片
     */
    async picPngSendHandler(file) {
      let url = window.URL.createObjectURL(file.file);
      let formData = new FormData();
      formData.append("file", file.file);
      let res = await commonAPI.upload(formData);
      let icon = res.data;
      let data = {
        messageType: 20,
        fromUser: this.$store.getters["user/getUserId"],
        toUser: this.topUserInfo.userId,
        msg: icon,
      };
      this.$socket.send(JSON.stringify(data));
      let data1 = {
        type: 1,
        content: url,
        image: this.avatar,
      };
      this.sendCount++;
      this.messageListChat.push(data1);
      this.$refs.main.scrollTop = this.$refs.main.scrollHeight;
    },

    testBlobUrl(content) {
      let reg = new RegExp("blob:http");
      return reg.test(content);
    },

    /**
     * @description 接收消息
     */
    async testData(receiveMessage) {
      if (receiveMessage.messageType === 4) {
        console.log(receiveMessage);
        this.$message.success("恭喜你们，成功建立好友关系");
        this.userList = [];
        //获取好友列表
        await chatAPI.getFriends().then((res) => {
          if (res.code === 1) {
            res.data.forEach((item) => {
              this.getFriendInfo(item.friendId);
            });
          }
        });
      }
      //发送申请
      else if (receiveMessage.messageType === 12) {
        if (receiveMessage.gameCategory === 0) {
          this.drawGuessObj.drawGuessConfirmVisible = true;
          this.drawGuessObj.drawGuessConfirm = receiveMessage.msg;
        }
        if (receiveMessage.gameCategory === 1) {
          this.realThinkObj.realThinkConfirmVisible = true;
          this.realThinkObj.realThinkConfirm = receiveMessage.msg;
        }
        if (receiveMessage.gameCategory === 2) {
          this.loveTalkObj.loveTalkConfirmVisible = true;
          this.loveTalkObj.loveTalkConfirm = receiveMessage.msg;
        }
        if (receiveMessage.gameCategory === 3) {
          this.storyDragonObj.storyDragonConfirmVisible = true;
          this.storyDragonObj.storyDragonConfirm = receiveMessage.msg;
        }
      }
      //收到视频聊天申请
      else if (receiveMessage.messageType === 21) {
        this.videoObj.videoDiaVisible = true;
        this.videoObj.videoConfirm = receiveMessage.msg;
      }
      //同意
      else if (receiveMessage.messageType === 13) {
        if (receiveMessage.gameCategory === 0) {
          this.drawGuessObj.drawGuessConfirmVisible = false;
        }
        if (receiveMessage.gameCategory === 1) {
          this.realThinkObj.realThinkConfirmVisible = false;
        }
        if (receiveMessage.gameCategory === 2) {
          this.loveTalkObj.loveTalkConfirmVisible = false;
          this.loveTalkObj.contest = Math.round(Math.random() * 2);

          let data = {
            messageType: 16,
            fromUser: this.$store.getters["user/getUserId"],
            toUser: this.topUserInfo.userId,
            gameCategory: 2,
            msg: this.loveTalkObj.contest,
          };
          console.log(data);
          this.$socket.send(JSON.stringify(data));
        }
        if (receiveMessage.gameCategory === 3) {
          this.storyDragonObj.isSend = true;
        }
        this.$message.success("对方已经同意你的申请");
      } else if (receiveMessage.messageType === 22) {
        this.videoObj.videoVisible = true;
        this.getLocalStream();
        this.$message.warning("对方接受了你的申请");
        //开始进行视频聊天相关信息传递
      } else if (receiveMessage.messageType === 23) {
        this.videoObj.videoVisible = false;
        this.$message.warning("很遗憾，对方拒绝了你的申请");
      } else if (receiveMessage.messageType === 24) {
        this.videoObj.videoVisible = true;
        // 收到A端Offer
        this.videoObj.remoteOffer = JSON.parse(receiveMessage.msg);
        console.log(this.videoObj.remoteOffer);
        // B端开始操作
        this.getLocalStreamB();
      } else if (receiveMessage.messageType === 25) {
        // 收到B端Answer
        this.videoObj.remoteOffer = JSON.parse(receiveMessage.msg);
        console.log("收到B端Answer：", this.videoObj.remoteOffer);
        this.videoObj.localPeer.setRemoteDescription(this.videoObj.remoteOffer);
      } else if (receiveMessage.messageType === 26) {
        // 收到A端candidate信息
        this.videoObj.remoteCandidate = JSON.parse(receiveMessage.msg);
        console.log("收到A端candidate信息：", this.videoObj.remoteCandidate);
        this.videoObj.localPeer.addIceCandidate(this.videoObj.remoteCandidate);
      } else if (receiveMessage.messageType === 27) {
        //收到B端candidate信息
        this.videoObj.remoteCandidate = JSON.parse(receiveMessage.msg);
        console.log("收到B端candidate信息：", this.videoObj.remoteCandidate);
        this.videoObj.localPeer.addIceCandidate(this.videoObj.remoteCandidate);
        this.videoObj.localPeer.onaddstream = (e) => {
          let remoteVideo = document.getElementById("remoteVideo");
          remoteVideo.srcObject = e.stream;
          remoteVideo.play();
        };
      } else if(receiveMessage.messageType === 28) {
        let localVideo = document.getElementById("localVideo");
        let remoteVideo = document.getElementById("remoteVideo");
        localVideo.srcObject.getTracks()[0].stop();
        remoteVideo.srcObject.getTracks()[0].stop();
        this.videoObj.videoVisible = false;
        this.$message.warning("对方关闭了视频聊天");
      }
      //拒绝
      else if (receiveMessage.messageType === 14) {
        if (receiveMessage.gameCategory === 0) {
          this.drawGuessObj.drawGuessVisible = false;
        }
        if (receiveMessage.gameCategory === 1) {
          this.realThinkObj.realThinkVisible = false;
        }
        if (receiveMessage.gameCategory === 2) {
          this.loveTalkObj.loveTalkVisible = false;
        }
        if (receiveMessage.gameCategory === 3) {
          this.storyDragonObj.storyDragonVisible = false;
        }
        this.$message.warning("很遗憾，对方拒绝了你的申请");
      }
      //退出
      else if (receiveMessage.messageType === 15) {
        if (receiveMessage.gameCategory === 0) {
          this.$message.warning("对方已经退出你画我猜游戏");
          this.drawGuessObj.drawGuessVisible = false;
          this.drawGuessObj.isReceiver = true;
          this.drawGuessObj.isSend = false;
          this.initialDrawGuess();
        }
        if (receiveMessage.gameCategory === 1) {
          this.realThinkObj.realThinkVisible = false;
          this.$message.warning("对方已经退出真心话");
        }
        if (receiveMessage.gameCategory === 2) {
          this.$message.warning("对方已经退出土味情话");
          this.loveTalkObj.loveTalkVisible = false;
        }
        if (receiveMessage.gameCategory === 3) {
          this.$message.warning("对方已经退出故事接龙");
          this.storyDragonObj.storyDragonVisible = false;
        }
      }
      //正常发送消息
      else if (receiveMessage.messageType === 16) {
        if (receiveMessage.gameCategory === 0) {
          if (receiveMessage.msg === "success") {
            this.drawGuessObj.isReceiver = false;
            this.$message.success("恭喜你，答对了");
            this.initialDrawGuess();
          } else if (receiveMessage.msg === "refuse") {
            this.drawGuessObj.isReceiver = false;
            this.$message.warning("很遗憾，你答错了");
            this.initialDrawGuess();
          } else {
            this.drawGuessObj.sendGuessContent = receiveMessage.msg;
          }
        }
        if (receiveMessage.gameCategory === 1) {
          this.realThinkObj.anotherAns = receiveMessage.msg;
        }
        if (receiveMessage.gameCategory === 2) {
          if (
            Number(receiveMessage.msg) === 0 ||
            Number(receiveMessage.msg) === 1 ||
            Number(receiveMessage.msg) === 2
          ) {
            this.loveTalkObj.contestAno = Number(receiveMessage.msg);
            this.loveTalkObj.canSend = this.justifyContest();
            if (this.loveTalkObj.canSend) {
              this.$message.info("请发送土味情话");
            } else {
              this.$message.info("等待对方土味情话");
            }
          } else {
            this.loveTalkObj.receiveLoveTalk = receiveMessage.msg;
            let data = {
              type: 0,
              image: this.topUserInfo.image,
              content: this.loveTalkObj.receiveLoveTalk,
            };
            this.loveTalkObj.chatList.push(data);
          }
        }
        if (receiveMessage.gameCategory === 3) {
          this.storyDragonObj.anoStory = receiveMessage.msg;
          let data = {
            type: 0,
            image: this.topUserInfo.image,
            content: this.storyDragonObj.anoStory,
          };
          this.storyDragonObj.listChat.push(data);
          this.storyDragonObj.isSend = true;
        }
      }
      //收到主题
      else if (receiveMessage.messageType === 17) {
        if (receiveMessage.gameCategory === 0) {
          this.drawGuessObj.title = receiveMessage.msg;
        }
        if (receiveMessage.gameCategory === 1) {
          if (this.realThinkObj.question !== "") {
            this.initialRealThink();
            this.realThinkObj.question = receiveMessage.msg;
          } else {
            this.realThinkObj.question = receiveMessage.msg;
          }
        }
        if (receiveMessage.gameCategory === 3) {
          this.storyDragonObj.storyStart = receiveMessage.msg;
        }
      }
      //收到icon
      else if (receiveMessage.messageType === 18) {
        await commonAPI.download(receiveMessage.msg).then((res) => {
          console.log(res);
          let binaryData = [];
          binaryData.push(res);
          this.drawGuessObj.receivePic = window.URL.createObjectURL(
            new Blob(binaryData)
          );
        });
      } else if (receiveMessage.messageType === 20) {
        await commonAPI.download(receiveMessage.msg).then((res) => {
          console.log(res);
          let binaryData = [];
          binaryData.push(res);
          let url = window.URL.createObjectURL(new Blob(binaryData));
          let data = {
            type: 0,
            content: url,
            image: this.topUserInfo.image,
          };
          this.messageListChat.push(data);
          this.sendCount++;
          this.$refs.main.scrollTop = this.$refs.main.scrollHeight;
        });
      }
      //收到下一轮猜拳信号
      else if (receiveMessage.messageType === 19) {
        this.loveTalkObj.contestAno = Number(receiveMessage.msg);
        this.loveTalkObj.contest = Math.round(Math.random() * 2);
        this.loveTalkObj.canSend = this.justifyContest();
        if (this.loveTalkObj.canSend) {
          this.$message.info("请发送土味情话");
        } else {
          this.$message.info("等待对方土味情话");
        }
        let data = {
          messageType: 16,
          fromUser: this.$store.getters["user/getUserId"],
          toUser: this.topUserInfo.userId,
          gameCategory: 2,
          msg: this.loveTalkObj.contest,
        };
        this.$socket.send(JSON.stringify(data));
      } else if (receiveMessage.messageType === 0) {
        this.addFriendVisible = true;
        this.addFriendMsg = receiveMessage.msg;
        this.addFriendId = receiveMessage.fromUser;
      } else if (receiveMessage.messageType === 11) {
        this.$message.warning("你已经被拒绝");
      } else if (receiveMessage === 7) {
        this.$message.warning("很遗憾你们没有建立好友关系");
      } else if (receiveMessage.messageType === 6) {
        this.$message.success("临时会话建立成功");
      } else if (receiveMessage.messageType === 2) {
        console.log(receiveMessage);
        this.topUserInfo.groupImageList.forEach((item) => {
          if (item.userId === receiveMessage.fromUser) {
            this.groupUserAvatar = item.image;
            let data = {
              type: 0,
              content: receiveMessage.msg,
              image: this.groupUserAvatar,
            };
            this.messageListChat.push(data);
            this.sendCount++;
            this.$refs.main.scrollTop = this.$refs.main.scrollHeight;
          }
        });
      } else if (receiveMessage.messageType === 8) {
        this.$message.warning("您已经被移除群聊");
        this.groupList = [];
        //获取群聊列表
        await chatAPI.getPersonalGroup().then((res) => {
          console.log(res);
          res.data.forEach((item, index) => {
            this.getGroupList(item, index);
          });
        });
      } else if (receiveMessage.messageType === 9) {
        this.$message.warning(receiveMessage.msg);
        this.groupList = [];
        //获取群聊列表
        await chatAPI.getPersonalGroup().then((res) => {
          console.log(res);
          res.data.forEach((item, index) => {
            this.getGroupList(item, index);
          });
        });
      } else if (receiveMessage.messageType === 10) {
        this.$message.success(receiveMessage.msg);
        this.groupList = [];
        //获取群聊列表
        await chatAPI.getPersonalGroup().then((res) => {
          console.log(res);
          res.data.forEach((item, index) => {
            this.getGroupList(item, index);
          });
        });
      } else {
        const emoTest = new RegExp("0x");
        let data = {
          type: 0,
          content: emoTest.test(receiveMessage.msg)
            ? String.fromCodePoint(receiveMessage.msg)
            : receiveMessage.msg,
          image: this.topUserInfo.image,
        };
        this.messageListChat.push(data);
        this.sendCount++;
        this.$refs.main.scrollTop = this.$refs.main.scrollHeight;
      }
    },

    /**
     * @description 点击进入对方主页
     */
    toUserPersonal() {
      if (this.listType === 0) {
        this.$router.push({
          path: "/personal",
          query: {
            userId: this.topUserInfo.id,
          },
        });
      }
    },

    //<!--------------------- 以下函数皆为绘制图片用到的工具函数 ------------------------------>
    initCanvas() {
      this.fabricObj = new fabric.Canvas("canvas", {
        isDrawingMode: true,
        selectable: false,
        selection: false,
        devicePixelRatio: true, //Retina 高清屏 屏幕支持
      });
      console.log(this.fabricObj);
      this.fabricObj.freeDrawingBrush.color = "#E34F51";
      this.fabricObj.freeDrawingBrush.width = 2;
      console.log(this.canvasWidth);
      this.fabricObj.setWidth(844);
      this.fabricObj.setHeight(500);
      //绑定画板事件
      this.fabricObjAddEvent();
    },
    //时间监听
    fabricObjAddEvent() {
      this.fabricObj.on({
        "mouse:down": (o) => {
          this.mouseFrom.x = o.pointer.x;
          this.mouseFrom.y = o.pointer.y;
          this.doDrawing = true;
        },
        "mouse:up": (o) => {
          this.mouseTo.x = o.pointer.x;
          this.mouseTo.y = o.pointer.y;
          this.drawingObject = null;
          this.moveCount = 1;
          this.doDrawing = false;
          this.updateModifications(true);
        },
        "mouse:move": (o) => {
          if (this.moveCount % 2 && !this.doDrawing) {
            //减少绘制频率
            return;
          }
          this.moveCount++;
          this.mouseTo.x = o.pointer.x;
          this.mouseTo.y = o.pointer.y;
          this.drawing();
        },
        //对象移动时间
        "object:moving": (e) => {
          e.target.opacity = 0.5;
        },
        //增加对象
        "object:added": () => {
          // debugger
        },
        "object:modified": (e) => {
          e.target.opacity = 1;
          // let object = e.target;
          this.updateModifications(true);
        },
        "selection:created": (e) => {
          if (e.target._objects) {
            //多选删除
            var etCount = e.target._objects.length;
            for (var etindex = 0; etindex < etCount; etindex++) {
              this.fabricObj.remove(e.target._objects[etindex]);
            }
          } else {
            //单选删除
            this.fabricObj.remove(e.target);
          }
          this.fabricObj.discardActiveObject(); //清楚选中框
          this.updateModifications(true);
        },
      });
    },
    //储存历史记录
    updateModifications(savehistory) {
      if (savehistory == true) {
        this.fabricHistoryJson.push(JSON.stringify(this.fabricObj));
      }
    },
    transformMouse(mouseX, mouseY) {
      return { x: mouseX / this.zoom, y: mouseY / this.zoom };
    },
    resetObj() {
      this.fabricObj.selectable = false;
      this.fabricObj.selection = false;
      this.fabricObj.skipTargetFind = true;
      //清除文字对象
      if (this.textboxObj) {
        this.textboxObj.exitEditing();
        this.textboxObj = null;
      }
    },
    handleTools(tools, idx) {
      this.initIdx = idx;
      this.currentTool = tools.name;
      this.fabricObj.isDrawingMode = false;
      this.resetObj();
      switch (tools.name) {
        case "pencil":
          this.fabricObj.isDrawingMode = true;
          break;
        case "remove":
          this.fabricObj.selection = true;
          this.fabricObj.skipTargetFind = false;
          this.fabricObj.selectable = true;
          break;
        case "reset":
          this.fabricObj.clear();
          break;
        default:
          break;
      }
    },
    drawing() {
      if (this.drawingObject) {
        this.fabricObj.remove(this.drawingObject);
      }
      let fabricObject = null;
      switch (this.currentTool) {
        case "pencil":
          this.fabricObj.isDrawingMode = true;
          break;
        case "line":
          fabricObject = new fabric.Line(
            [
              this.mouseFrom.x,
              this.mouseFrom.y,
              this.mouseTo.x,
              this.mouseTo.y,
            ],
            {
              stroke: this.drawColor,
              strokeWidth: this.drawWidth,
            }
          );
          break;
        case "arrow":
          fabricObject = new fabric.Path(
            this.drawArrow(
              this.mouseFrom.x,
              this.mouseFrom.y,
              this.mouseTo.x,
              this.mouseTo.y,
              15.5,
              15.5
            ),
            {
              stroke: this.drawColor,
              fill: "rgba(255,255,255,0)",
              strokeWidth: this.drawWidth,
            }
          );
          break;
        case "dashedline":
          // doshed line
          fabricObject = this.drawDoshedLine();
          break;
        case "rectangle":
          // 矩形
          fabricObject = this.drawRectangle();
          break;
        case "circle": //正圆
          fabricObject = this.drawCircle();
          break;
        case "ellipse":
          // 椭圆
          fabricObject = this.drawEllipse();
          break;
        case "equilateral": //等边三角形
          fabricObject = this.drawTriangle();
          break;
        case "remove":
          break;
        default:
          // statements_def'
          break;
      }
      if (fabricObject) {
        this.$nextTick(() => {
          this.fabricObj.add(fabricObject);
          this.drawingObject = fabricObject;
        });
      }
    },
    // dashed line
    drawDoshedLine() {
      return new fabric.Line(
        [this.mouseFrom.x, this.mouseFrom.y, this.mouseTo.x, this.mouseTo.y],
        {
          strokeDashArray: [10, 3],
          stroke: this.drawColor,
          strokeWidth: this.drawWidth,
        }
      );
    },
    // circle
    drawCircle() {
      let radius =
        Math.sqrt(
          (this.mouseTo.x - this.mouseFrom.x) *
            (this.mouseTo.x - this.mouseFrom.x) +
            (this.mouseTo.y - this.mouseFrom.y) *
              (this.mouseTo.y - this.mouseFrom.y)
        ) / 2;
      return new fabric.Circle({
        left: this.mouseFrom.x,
        top: this.mouseFrom.y,
        stroke: this.drawColor,
        fill: "rgba(255, 255, 255, 0)",
        radius: radius,
        strokeWidth: this.drawWidth,
      });
    },
    // triangle
    drawTriangle() {
      let height = this.mouseTo.y - this.mouseFrom.y;
      return new fabric.Triangle({
        top: this.mouseFrom.y,
        left: this.mouseFrom.x,
        width: Math.sqrt(Math.pow(height, 2) + Math.pow(height / 2.0, 2)),
        height: height,
        stroke: this.drawColor,
        strokeWidth: this.drawWidth,
        fill: "rgba(255,255,255,0)",
      });
    },
    // ellipse
    drawEllipse() {
      let left = this.mouseFrom.x;
      let top = this.mouseFrom.y;
      // let ellipse = Math.sqrt((this.mouseTo.x - left) * (this.mouseTo.x - left) + (this.mouseTo.y - top) * (this.mouseTo.y - top)) / 2;
      return new fabric.Ellipse({
        left: left,
        top: top,
        stroke: this.drawColor,
        fill: "rgba(255, 255, 255, 0)",
        originX: "center",
        originY: "center",
        rx: Math.abs(left - this.mouseTo.x),
        ry: Math.abs(top - this.mouseTo.y),
        strokeWidth: this.drawWidth,
      });
    },
    // rectangle
    drawRectangle() {
      return new fabric.Rect({
        left: this.mouseFrom.x,
        top: this.mouseFrom.y,
        width: this.mouseTo.x - this.mouseFrom.x,
        height: this.mouseTo.y - this.mouseFrom.y,
        fill: "rgba(255, 255, 255, 0)",
        stroke: this.drawColor,
        strokeWidth: this.drawWidth,
      });
    },
    //书写箭头的方法
    drawArrow(fromX, fromY, toX, toY, theta, headlen) {
      theta = typeof theta != "undefined" ? theta : 30;
      headlen = typeof theta != "undefined" ? headlen : 10;
      // 计算各角度和对应的P2,P3坐标
      let angle = (Math.atan2(fromY - toY, fromX - toX) * 180) / Math.PI,
        angle1 = ((angle + theta) * Math.PI) / 180,
        angle2 = ((angle - theta) * Math.PI) / 180,
        topX = headlen * Math.cos(angle1),
        topY = headlen * Math.sin(angle1),
        botX = headlen * Math.cos(angle2),
        botY = headlen * Math.sin(angle2);
      let arrowX = fromX - topX,
        arrowY = fromY - topY;
      let path = " M " + fromX + " " + fromY;
      path += " L " + toX + " " + toY;
      arrowX = toX + topX;
      arrowY = toY + topY;
      path += " M " + arrowX + " " + arrowY;
      path += " L " + toX + " " + toY;
      arrowX = toX + botX;
      arrowY = toY + botY;
      path += " L " + arrowX + " " + arrowY;
      return path;
    },

    //<!--------------------- 视频聊天相关函数 ------------------------------>
    /**
     * @description 发送视频聊天请求
     */
    sendVideoReq() {
      if (!this.videoObj.videoVisible) {
        this.videoObj.isReceiver = false;
        let data = {
          messageType: 21,
          fromUser: this.$store.getters["user/getUserId"],
          toUser: this.topUserInfo.userId,
          msg:
            "收到" + this.$store.getters["user/getUserName"] + "视频聊天申请",
        };
        this.$socket.send(JSON.stringify(data));
      }else {
        let localVideo = document.getElementById("localVideo");
        let remoteVideo = document.getElementById("remoteVideo");
        localVideo.srcObject.getTracks()[0].stop();
        remoteVideo.srcObject.getTracks()[0].stop();
        this.videoObj.videoVisible = false;
        let data = {
          messageType: 28,
          fromUser: this.$store.getters["user/getUserId"],
          toUser: this.topUserInfo.userId,
        };
        this.$socket.send(JSON.stringify(data));
      }
    },

    confirmVideo(type) {
      if (type === 1) {
        this.videoObj.videoDiaVisible = false;
        let data = {
          messageType: 22,
          fromUser: this.$store.getters["user/getUserId"],
          toUser: this.topUserInfo.userId,
        };
        this.$socket.send(JSON.stringify(data));
        this.$message.success("好的，现在你们可以进行视频聊天了, 请等待");
      } else {
        this.videoObj.videoDiaVisible = false;
        let data = {
          noteId: null,
          messageType: 23,
          fromUser: this.$store.getters["user/getUserId"],
          toUser: this.topUserInfo.userId,
        };
        this.$socket.send(JSON.stringify(data));
      }
    },

    /**
     * @description 视频申请成功后的逻辑
     */
    getLocalStream() {
      let mediaOpts = {
        video: true,
      };
      let _this = this;
      function successFunc(stream) {
        let video = document.getElementById("localVideo");
        _this.videoObj.localStream = stream;
        video.srcObject = stream;
        video.play();
        _this.getLocalOffer();
      }
      function errorFunc(err) {}
      navigator.getUserMedia(mediaOpts, successFunc, errorFunc);
    },

    /**
     * @description 申请本地端offer
     */
    async getLocalOffer() {
      this.videoObj.localPeer = new RTCPeerConnection();
      this.videoObj.localPeer.onicecandidate = (e) => {
        if (e.candidate) {
          console.log("A的candidate信息:", e.candidate);
          let data = {
            messageType: 26,
            fromUser: this.$store.getters["user/getUserId"],
            toUser: this.topUserInfo.userId,
            msg: JSON.stringify(e.candidate),
          };
          this.$socket.send(JSON.stringify(data));
        }
      };
      this.videoObj.localPeer.addStream(this.videoObj.localStream);
      const offer = await this.videoObj.localPeer.createOffer({
        offerToReceiveVideo: 1,
      });
      await this.videoObj.localPeer.setLocalDescription(offer);
      let data = {
        messageType: 24,
        fromUser: this.$store.getters["user/getUserId"],
        toUser: this.topUserInfo.userId,
        msg: JSON.stringify(offer),
      };
      this.$socket.send(JSON.stringify(data));
    },

    /**
     * @description 视频申请成功后的逻辑
     */
    getLocalStreamB() {
      let mediaOpts = {
        video: true,
      };
      let _this = this;
      function successFunc(stream) {
        let video = document.getElementById("localVideo");
        _this.videoObj.localStream = stream;
        video.srcObject = stream;
        video.play();
        _this.getVideoAnswer();
      }
      function errorFunc(err) {}
      navigator.getUserMedia(mediaOpts, successFunc, errorFunc);
    },

    /**
     * @description B端生成answer
     */
    async getVideoAnswer() {
      this.videoObj.localPeer = new RTCPeerConnection();
      this.videoObj.localPeer.onaddstream = (e) => {
        console.log("B端成功监听");
        let remoteVideo = document.getElementById("remoteVideo");
        remoteVideo.srcObject = e.stream;
        remoteVideo.play();
      };
      this.videoObj.localPeer.onicecandidate = (e) => {
        if (e.candidate) {
          console.log("B的candidate信息:", e.candidate);
          let data = {
            messageType: 27,
            fromUser: this.$store.getters["user/getUserId"],
            toUser: this.topUserInfo.userId,
            msg: JSON.stringify(e.candidate),
          };
          this.$socket.send(JSON.stringify(data));
        }
      };
      this.videoObj.localPeer.addStream(this.videoObj.localStream);
      await this.videoObj.localPeer.setRemoteDescription(
        this.videoObj.remoteOffer
      );
      const answer = await this.videoObj.localPeer.createAnswer();
      this.videoObj.localPeer.setLocalDescription(answer);
      let data = {
        messageType: 25,
        fromUser: this.$store.getters["user/getUserId"],
        toUser: this.topUserInfo.userId,
        msg: JSON.stringify(answer),
      };
      console.log(data);
      this.$socket.send(JSON.stringify(data));
    },
  },
};
</script>

<style lang="scss" scoped>
::-webkit-scrollbar-track {
  background: rgba(26, 10, 165, 0.1);
  border-radius: 15%;
}

::-webkit-scrollbar {
  -webkit-appearance: none;
  width: 9px;
  height: 1px;
}

::-webkit-scrollbar-thumb {
  cursor: pointer;
  border-radius: 50%;
  background: rgba(4, 245, 68, 0.15);
  transition: color 0.2s ease;
}
#header {
  width: 100%;
  height: 40px;
  background-color: black;
}
.logoText {
  color: #fcdd44;
  font-size: 27px;
  font-weight: lighter;
  text-transform: uppercase;
  line-height: 40px;
  margin-right: 82%;
  font-family: "STXingkai";
}
.logoText:hover,
.logoText:focus {
  color: #ff720b;
  cursor: pointer;
}
.logo {
  height: 50px;
  width: 50px;
  margin: auto;
  margin-top: 32%;
  margin-bottom: 0%;
}

.logo:hover {
  transform: scale(1.3);
  cursor: pointer;
}
.userAvatar {
  height: 35px;
  width: 35px;
  border-radius: 50%;
  margin: auto;
  margin-top: 70%;
  margin-bottom: 0%;
}
.loveTalkMyAvatar {
  height: 50px;
  width: 50px;
  border-radius: 50%;
  margin-right: 8%;
}
.userAvatar:hover {
  transform: scale(1.3);
  cursor: pointer;
}
.icon {
  height: 25px;
  width: 25px;
  margin: auto;
  margin-top: 50%;
  margin-bottom: 0%;
}

.icon:hover {
  transform: scale(1.5);
  border: #21aa93 dashed 3px;
  cursor: pointer;
}
.friendAndMessageList {
  width: 26.8%;
  margin-left: 0.1%;
  margin-right: 0.1%;
  background-color: #f3f2ef;
  display: flex;
  flex-direction: column;
}
.FMTitle {
  color: #21aa93;
  font-weight: bold;
  font-size: 26px;
  margin-right: 70%;
  margin-top: 6%;
  font-family: "STZhongsong";
}
.search {
  width: 85%;
  height: 40px;
  margin-left: 7%;
  margin-top: 5%;
}
.subTitle {
  margin-right: 52%;
  margin-top: 4%;
  margin-bottom: 2%;
  font-size: 14px;
  color: #626569;
}
.friendInfo {
  background-color: #fff;
  border-radius: 0.25rem;
  width: 85%;
  height: 75px;
  margin-left: 7%;
  margin-bottom: 1.5%;
  display: flex;
  flex-direction: row;
}
.friendInfo:hover {
  border: 1px solid #21aa93;
  cursor: pointer;
}
.AvatarBox {
  width: 25%;
}
.friendAvatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-top: 15%;
}
.friendContent {
  display: flex;
  flex-direction: column;
}
.username {
  margin: auto;
  margin-bottom: 0%;
  margin-left: 0%;
  font-size: 16px;
  font-weight: 600;
  color: #555555;
}
.username2 {
  margin: auto;
  margin-top: 25px;
  margin-left: 0%;
  font-size: 16px;
  font-weight: 600;
  color: #555555;
}
.content {
  margin: auto;
  margin-top: 0%;
  margin-left: 0%;
  font-size: 13px;
  color: #626569;
}
.chatAvatar {
  width: 70px;
  height: 70px;
  border-radius: 50%;
  margin: auto;
  margin-top: 25%;
}
.chatFriendAvatar {
  position: absolute;
  width: 45px;
  height: 45px;
  border-radius: 50%;
  left: 5%;
  top: 2.3%;
}

.chatFriendAvatar:hover {
  cursor: pointer;
}
.chatFriendName {
  position: absolute;
  left: 11%;
  top: 2.3%;
  color: #555555;
  font-weight: bold;
}
.chatFriendState {
  position: absolute;
  left: 11%;
  top: 6%;
  font-size: 13px;
  color: #555555;
  font-weight: lighter;
}
.infinite-list {
  height: 500px;
  padding: 0;
  margin: 0;
  list-style: none;
}
.chatBox {
  width: 100%;
  display: flex;
  flex-direction: row;
  margin-bottom: 20px;
}
.chatBox_Avatar {
  left: 3%;
  top: 10%;
  width: 40px;
  height: 40px;
  margin-top: 2%;
  border-radius: 50%;
  border: #21aa93 solid 3px;
}
.chatBox_Message {
  display: flex;
  background: #1770c3;
  color: #fff;
  font-family: "KaiTi";
  border-radius: 10px;
  border-top-left-radius: 0px;
  max-width: 40%;
  padding: 0.8%;
  left: 7.5%;
  top: 26%;
  text-align: left;
  box-shadow: darkgrey 5px 5px 15px -5px;
  margin-top: 5.5%;
  margin-left: 3%;
}
.chatBox1 {
  width: 100%;
  display: flex;
  flex-direction: row;
  margin-bottom: 20px;
  flex-direction: row-reverse;
}
.chatBox_Avatar1 {
  left: 0%;
  top: 10%;
  margin-right: 3%;
  width: 40px;
  height: 40px;
  margin-top: 2%;
  border-radius: 50%;
  border: #21aa93 solid 3px;
}
.chatBox_Message1 {
  display: flex;
  background: #1770c3;
  color: #fff;
  font-family: "KaiTi";
  border-radius: 10px;
  border-top-right-radius: 0px;
  max-width: 40%;
  padding: 0.8%;
  left: 7.5%;
  top: 26%;
  text-align: left;
  box-shadow: darkgrey 5px 5px 15px -5px;
  margin-top: 5.5%;
  margin-left: 3%;
}
.inputMessage {
  position: absolute;
  border: none;
  outline: none;
  height: 95px;
  width: 100%;
  left: 0%;
  top: 2%;
}
.chatFriendInfo {
  width: 80%;
  height: 80px;
  position: relative;
  margin-left: 18%;
}
.chatFriendInfo_icon {
  width: 30px;
  height: 30px;
  position: absolute;
}
.chatFriendInfo_icon:hover {
  cursor: pointer;
}
.chatFriendInfo_icon_add {
  width: 30px;
  height: 30px;
  position: absolute;
}
.chatFriendInfo_icon_add:hover {
  cursor: pointer;
}
.chatFriendInfo_group {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  position: absolute;
}
.chatFriendInfo_group:hover {
  cursor: pointer;
}
.chatFriendInfo_text {
  font-size: 22px;
  font-family: "KaiTi";
  position: absolute;
}

/**以下皆为游戏所用样式*/
.black_overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
}
.game1 {
  width: 300px;
  height: 100px;
  margin-top: 1%;
}

.wraper {
  position: relative;
  width: 100%;
  height: 100%;
  margin-top: 0%;
  .canvas-wraper {
    height: 50%;
    width: 50%;
    margin-left: 27%;
    margin-bottom: 10px;
    overflow: hidden;
  }
  .canvas-wraper2 {
    height: 50%;
    width: 50%;
    margin-left: 3%;
    margin-bottom: 10px;
    overflow: hidden;
  }
  .controlPanel {
    position: absolute;
    width: 50px;
    left: 24%;
    top: 0%;
    background: #ddd;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin-bottom: 15px;
    .contro-item {
      width: 50px;
      height: 50px;
      border-right: 1px solid #dad7d9;
      text-align: center;
      cursor: pointer;
      background: #fefefe;
      i {
        font-size: 38px;
        line-height: 62px;
      }
      &.active {
        background: #e34f51;
        color: #fff;
        border-radius: 3px;
        i {
          font-size: 42px;
        }
      }
    }
  }
  .download {
    img {
      width: 100%;
    }
  }
}

.drawGuessSend {
  width: 10%;
}

.realThinkBackGround {
  width: 900px;
  height: 600px;
  margin: auto;
  margin-top: 4%;
  background-size: 100%;
  display: flex;
  flex-direction: column;
}

.storyDragonBackGround {
  width: 960px;
  height: 360px;
  margin: auto;
  margin-top: 2%;
  background-size: 100% 100%;
  display: flex;
  flex-direction: column;
}

.realThinkQuestion {
  margin-top: 12%;
  font-size: 50px;
  font-family: "隶书";
  color: #fff;
}

.realThink {
  width: 300px;
  height: 100px;
  border-radius: 2%;
  margin-bottom: 2%;
  display: flex;
  flex-direction: column;
}

.drawGuessTitle {
  font-size: 30px;
  color: #fff;
}

.realThinkInput {
  margin: auto;
  margin-top: 1%;
  margin-bottom: 1%;
  width: 50%;
}

.realThinkButton {
  display: flex;
  flex-direction: row;
  justify-content: center;
  margin-top: 5%;
}

.realThinkButtonItem {
  background-color: black;
  color: white;
  opacity: 0.8;
  width: 142px;
}

.loveTalkCompete {
  width: 300px;
  height: 516px;
  margin-right: 5%;
  background-color: white;
  border-radius: 20px;
}

.loveTalkChat {
  width: 500px;
  height: 500px;
  background-color: white;
  margin-right: 5%;
}

.loveTalkTemplate {
  width: 300px;
  height: 516px;
  background-color: gray;
  border-radius: 20px;
}

.loveTalkGuess {
  width: 200px;
  height: 200px;
}

.loveTalkMyAvatar {
  height: 50px;
  width: 50px;
  border-radius: 50%;
  margin-right: 8%;
}

.storyDragonChat {
  width: 960px;
  height: 140px;
  background-color: white;
  margin: auto;
}

.specialBox {
  height: 25px;
  display: flex;
  align-items: center;
  // background-color: #e34f51;
}

.emoPng {
  width: 20px;
  height: 20px;
  margin-left: 10px;
}

.emoPng:hover {
  background-color: #dad7d9;
  cursor: pointer;
}

.picPng {
  width: 20px;
  height: 20px;
  margin-left: 15px;
}

.picPng:hover {
  background-color: #dad7d9;
  cursor: pointer;
}

.videoPng {
  width: 20px;
  height: 20px;
  margin-left: 15px;
}

.videoPng:hover {
  background-color: #dad7d9;
  cursor: pointer;
}

.emoBox {
  position: absolute;
  height: 150px;
  width: 400px;
  background-color: #fff;
  top: -150px;
  display: flex;
  flex-wrap: wrap;
  display: flex;
  overflow: auto;
  border: #21aa93 solid 1px;
  border-right: 0px;
}

.emojiChar {
  width: 30px;
  height: 30px;
}

.emojiChar:hover {
  background-color: #dad7d9;
  cursor: pointer;
}

.localVideo {
  width: 49%;
}

.remoteVideo {
  width: 49%;
}
</style>
